<template>
  <!-- index -> add-role -> el-dialog -->
  <el-dialog :visible="showDialog" @close="closeDialog">
    <template #default>
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
    </template>

    <!-- 底部 -->
    <template #footer>
      <el-row slot="footer" type="flex" justify="center">
        <el-button size="small">取消</el-button>
        <el-button size="small" type="primary" @click="confirmAdd">确定</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { addRole, getRoleDetail, updateRole } from '@/api/setting'
export default {
  props: {
    showDialog: {
      type: Boolean
    },
    curId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    closeDialog() {
      console.log('点击叉号')
      this.$emit('close-dialog')
    },
    confirmAdd() {
      // 兜底校验
      // 调用接口
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          if (this.roleForm.id) {
            await updateRole(this.roleForm)
            this.$message.success('修改成功')
          } else {
            await addRole(this.roleForm)
          }
          // 后续逻辑
          // 关闭弹框
          this.closeDialog()
          // 清除数据
          this.$message.success('添加成功')
          this.$refs.roleForm.resetFields()
          // 更新列表
          this.$emit('update-list')
        }
      })
    },
    // open打开弹框时 调用此接口
    // this.$refs.xxx 组件的实例对象 调用实例上的任何方法
    async fetchDetail(id) {
      const res = await getRoleDetail(id)
      this.roleForm = res
    }
    // dialogOpen() {
    //   this.fetchDetail()
    // }
  }
}
</script>
